#include("/common/_layout.html")
#@layout()
#define layoutHead()
<link rel="stylesheet" type="text/css" href="/static/other/webuploader-0.1.5/webuploader.css">
<title>课程详情</title>
<style>
	.div_add_class{display: none; margin: 10px;}
		.upfilediv{display: none;}
	</style>
#end
#define layoutBody()
<body>
	<div class="page-content-wrap">
		<div class="layui-form">
			<div class="layui-tab" style="margin: 0;">
				<ul class="layui-tab-title">
					<li><a id="a_goback_url" href="javascript:window.history.back();">课程列表</a></li>
					<li class="layui-this">课程详情</li>
				</ul>
				<div class="layui-tab-content" id="mainDivClass">
					<div class="layui-tab-item"></div>
					<div class="layui-tab-item layui-show">
						<div class="layui-form-item">
							<div class="layui-inline">
								<img id="front_cover_url" src="" width="100" height="100">
							</div>
							<div class="layui-inline">
								<div id="div_course_name" style="line-height: 33px; font-size:22px; font-weight:bold;"></div>
								<div id="div_lecturer_name" style="line-height: 33px;">主讲老师：</div>
								<div id="div_subject_name" style="line-height: 33px;">课程科目：</div>
							</div>
							<div class="layui-inline">
								<div id="div_add_time" style="line-height: 33px; margin-top:33px;">创建时间：</div>
								<div id="div_power_id" style="line-height: 33px;"> 发布对象：</div>
							</div>
						</div>
						<div class="layui-form-item">
							<div class="layui-inline">
								<button id="btn_addclass" class="layui-btn layui-btn-mini layui-btn-primary add-class">+ 添加课节</button>
							</div>
						</div>
						<div class="layui-form-item" id="showListClass">
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<div id="div_add_class" class="div_add_class">
		<form class="layui-form" lay-filter="formclass">
			<input type="hidden" id="course_id" name="course_id">
			<input type="hidden" id="class_id" name="class_id">
			<input type="hidden" id="parent_id" name="parent_id">
			<input type="hidden" id="class_typeid" name="class_typeid">
			<div class="layui-form-item">
				<label class="layui-form-label" id="colname_1st">课节名称：</label>
				<div class="layui-input-block">
					<input type="text" name="class_title" placeholder="请输入名称" required lay-verify="required" autocomplete="off" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">排序：</label>
				<div class="layui-input-block">
					<input type="text" name="class_sort" placeholder="请输入排序" required lay-verify="required" autocomplete="off" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item upfilediv">
				<label class="layui-form-label">文件类型：</label>
				<div class="layui-input-block">
					<select id="file_type" name="file_type">
						<option value="">请选择</option>
						<option value="1">视频</option>
						<option value="2">音频</option>
						<option value="3">图片</option>
						<option value="4">文件</option>
					</select>
				</div>
			</div>
			<div class="layui-form-item upfilediv">
				<label class="layui-form-label">时长(分钟)：</label>
				<div class="layui-input-block">
					<input type="text" name="time_len" placeholder="单位:分钟, 音视频时长, 非媒体文件请置空" autocomplete="off" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item upfilediv">
				<label class="layui-form-label">上传文件：</label>
				<div class="layui-input-block">
					<input type="text" id="file_url" name="file_url" placeholder="请输入文件URL,或点击[上传文件]按钮上传" class="layui-input">
					<input type="hidden" id="file_len" name="file_len">
					<input type="hidden" id="file_type1" name="file_type1">
					<br>
					<input type="file" name="file_file_url" lay-ext="jpeg|jpg|png|gif|doc|docx|xls|xlsx|ppt|pptx|txt|pdf|mp4|3gp|flv|mpeg4|wma|mp3"
					 lay-type="file" lay-title="上传文件" class="layui-upload-file" style="display: none;">
					<div id="div_file_url" style="padding: 5px; display: none;"></div>
					
					<!-- webuploader -->
					<div id="upload_picker" class="webuploader-container" style="float: left; margin-right: 10px">
                        <div> 选择文件 <input type="file" name="file" class="webuploader-element-invisible" multiple="multiple">
                        </div>
                    </div>

                    <div id="upload_start" class="webuploader-pick" style="float: left; margin-right: 10px">开始上传</div>
                    <div id="upload_stop" class="webuploader-pick" style="float: left; margin-right: 10px" status="suspend">暂停上传</div>
					<div id="upload_files" class="uploader-list"></div>
					<!-- webuploader -->
				</div>
			</div>
			<div class="layui-form-item" style="padding-left: 10px;">
				<div class="layui-input-block">
					<button class="layui-btn layui-btn-normal" lay-submit lay-filter="formDemo">立即提交</button>

				</div>
			</div>
		</form>
	</div>

	<!-- #[[ -->
	<script id="tplListClass" type="text/html">
		<table class="layui-table" lay-even lay-skin="nob">
				  <colgroup>
					<col>
					<col width="60">
					<col width="60">
					<col width="50">
					<col width="50">
				</colgroup>
				  <thead>
					<tr>
					  <th>{{ d.p.class_sort }}. {{ d.p.class_title }}</th>
					  <th><button class="layui-btn layui-btn-mini layui-btn-primary add-class" data-id="{{ d.p.class_id }}">+ 添加点播</button></th>
					  <th><button class="layui-btn layui-btn-mini layui-btn-primary add-class" data-id="{{ d.p.class_id }}">+ 添加资料</button></th>
					  <th>
						  <button class="layui-btn layui-btn-mini layui-btn-normal edit-class" data-id="{{ d.p.class_id }}">* 编辑</button></th>
					  <th>
						  <button class="layui-btn layui-btn-mini layui-btn-danger del-class" data-id="{{ d.p.class_id }}">- 删除</button>
					  </th>
					</tr> 
				  </thead>
				  <tbody>
					  {{#  layui.each(d.listdata, function(index, item){ }}
						<tr>
						  <td><i class="layui-icon">{{ findFileIcon(item.file_type) }}</i> <a href="{{ item.file_url }}" target="_blank">{{ item.class_title }} {{ formatUpFileLen(item) }}</a></td>
						  <td></td>
						  <td></td>
						  <td>
							  <button class="layui-btn layui-btn-mini layui-btn-primary edit-class" data-id="{{ item.class_id }}">* 编辑</button>
							  </td>
						  <td>
							  <button class="layui-btn layui-btn-mini layui-btn-primary del-class" data-id="{{ item.class_id }}">- 删除</button>
						  </td>
						</tr>
					  {{#  }); }}
				  </tbody>
			</table>
		</script>
	<!-- ]]# -->
	<script src="/static/js/jquery.formHelp.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript" src="/static/other/webuploader-0.1.5/webuploader.min.js"></script>
	<script>
		/*********************************WebUpload 单文件上传 begin*****************************************/
		$(function () {
            $list = $('#upload_files');
            var flie_count = 0;
            var uploader = WebUploader.create({
                //设置选完文件后是否自动上传
                auto: false,
                //swf文件路径
                swf: '/static/other/webuploader/Uploader.swf',
                // 文件接收服务端。
                server: '/api/file/bigUpload',
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                pick: '#upload_picker',
                chunked: true, //开启分块上传
                chunkSize: 10 * 1024 * 1024,
                chunkRetry: 3,//网络问题上传失败后重试次数
                threads: 1, //上传并发数
                //fileNumLimit :1,
                fileSizeLimit: 2000 * 1024 * 1024,//最大2GB
                fileSingleSizeLimit: 2000 * 1024 * 1024,
                resize: false//不压缩
                //选择文件类型
                //accept: {
                //    title: 'Video',
                //    extensions: 'mp4,avi',
                //    mimeTypes: 'video/*'
                //}
            });
            // 当有文件被添加进队列的时候
            uploader.on('fileQueued', function (file) {
                $list.append('<div id="' + file.id + '" class="item">' +
                        '<h4 class="info">' + file.name + '<button type="button" fileId="' + file.id + '" class="btn btn-danger btn-delete"><span class="glyphicon glyphicon-trash"></span></button></h4>' +
                        '<p class="state">正在计算文件MD5...请等待计算完毕后再点击上传！</p><input type="text" id="s_WU_FILE_'+flie_count+'" />' +
                        '</div>');
						
						
                console.info("id=file_"+flie_count);
                flie_count++;
                
                //删除要上传的文件
                //每次添加文件都给btn-delete绑定删除方法
                $(".btn-delete").click(function () {
                    //console.log($(this).attr("fileId"));//拿到文件id
                    uploader.removeFile(uploader.getFile($(this).attr("fileId"), true));
                    $(this).parent().parent().fadeOut();//视觉上消失了
                    $(this).parent().parent().remove();//DOM上删除了
                });
                //uploader.options.formData.guid = WebUploader.guid();//每个文件都附带一个guid，以在服务端确定哪些文件块本来是一个
                //console.info("guid= "+WebUploader.guid());
                
                //md5计算
                uploader.md5File(file)
                    .progress(function(percentage) {
                      console.log('Percentage:', percentage);
                    })
                    // 完成
                    .then(function (fileMd5) { // 完成
                        var end = +new Date();
                        console.log("before-send-file  preupload: file.size="+file.size+" file.md5="+fileMd5);
                        file.wholeMd5 = fileMd5;//获取到了md5
                        //uploader.options.formData.md5value = file.wholeMd5;//每个文件都附带一个md5，便于实现秒传
                        
                        $('#' + file.id).find('p.state').text('MD5计算完毕，可以点击上传了');
                        console.info("MD5="+fileMd5);
                    });
                
                
            });
            // 文件上传过程中创建进度条实时显示。
            uploader.on('uploadProgress', function (file, percentage) {
                var $li = $('#' + file.id),
                        $percent = $li.find('.progress .progress-bar');
                // 避免重复创建
                if (!$percent.length) {
                    $percent = $('<div class="progress progress-striped active">' +
                            '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                            '</div>' +
                            '</div>').appendTo($li).find('.progress-bar');
                }
                $li.find('p.state').text('上传中');
                $percent.css('width', percentage * 100 + '%');
            });
            
            //发送前填充数据
            uploader.on( 'uploadBeforeSend', function( block, data ) {
                // block为分块数据。

                // file为分块对应的file对象。
                var file = block.file;
                var fileMd5 = file.wholeMd5;
                // 修改data可以控制发送哪些携带数据。
                
                console.info("fileName= "+file.name+" fileMd5= "+fileMd5+" fileId= "+file.id);
                console.info("input file= "+ flie_count);
                // 将存在file对象中的md5数据携带发送过去。
                data.md5value = fileMd5;//md5
                data.fileName_ = $("#s_"+file.id).val();
                console.log("fileName_: "+data.fileName_);
                // 删除其他数据
                // delete data.key;
                if(block.chunks>1){ //文件大于chunksize 分片上传
                    data.isChunked = true;
                    console.info("data.isChunked= "+data.isChunked);
                }else{
                    data.isChunked = false;
                    console.info("data.isChunked="+data.isChunked);
                }

            });
            
            
            uploader.on('uploadSuccess', function (file) {
                $('#' + file.id).find('p.state').text('已上传');
                $('#' + file.id).find(".progress").find(".progress-bar").attr("class", "progress-bar progress-bar-success");
                $('#' + file.id).find(".info").find('.btn').fadeOut('slow');//上传完后删除"删除"按钮
                $('#upload_stop').fadeOut('slow');
            });
            uploader.on('uploadError', function (file) {
                $('#' + file.id).find('p.state').text('上传出错');
                //上传出错后进度条变红
                $('#' + file.id).find(".progress").find(".progress-bar").attr("class", "progress-bar progress-bar-danger");
                //添加重试按钮
                //为了防止重复添加重试按钮，做一个判断
                //var retrybutton = $('#' + file.id).find(".btn-retry");
                //$('#' + file.id)
                if ($('#' + file.id).find(".btn-retry").length < 1) {
                    var btn = $('<button type="button" fileid="' + file.id + '" class="btn btn-success btn-retry"><span class="glyphicon glyphicon-refresh"></span></button>');
                    $('#' + file.id).find(".info").append(btn);//.find(".btn-danger")
                }
                $(".btn-retry").click(function () {
                    //console.log($(this).attr("fileId"));//拿到文件id
                    uploader.retry(uploader.getFile($(this).attr("fileId")));
                });
            });
            uploader.on('uploadComplete', function (file) {//上传完成后回调
                //$('#' + file.id).find('.progress').fadeOut();//上传完删除进度条
                //$('#' + file.id + 'btn').fadeOut('slow')//上传完后删除"删除"按钮
            });
            uploader.on('uploadFinished', function () {
                //上传完后的回调方法
                //alert("所有文件上传完毕");
                //提交表单
            });
            $("#upload_start").click(function () {
                uploader.upload();//上传
            });
            $("#upload_stop").click(function () {
                console.log($('#upload_stop').attr("status"));
                var status = $('#upload_stop').attr("status");
                if (status == "suspend") {
                    console.log("当前按钮是暂停，即将变为继续");
                    $("#upload_stop").html("继续上传");
                    $("#upload_stop").attr("status", "continuous");
                    console.log("当前所有文件==="+uploader.getFiles());
                    console.log("=============暂停上传==============");
                    uploader.stop(true);
                    console.log("=============所有当前暂停的文件=============");
                    console.log(uploader.getFiles("interrupt"));
                } else {
                    console.log("当前按钮是继续，即将变为暂停");
                    $("#upload_stop").html("暂停上传");
                    $("#upload_stop").attr("status", "suspend");
                    console.log("===============所有当前暂停的文件==============");
                    console.log(uploader.getFiles("interrupt"));
                    uploader.upload(uploader.getFiles("interrupt"));
                }
            });
            uploader.on('uploadAccept', function (file, response) {
                if (response._raw === '{"error":true}') {
                    return false;
                }
            });
        });
		/*********************************WebUpload 单文件上传 end*******************************************/

		/************************************webuploader的自带参数提交到后台的参数列表*************************
		 * {

		//web uploader 的自带参数 
		lastModifiedDate=[Wed Apr 27 2016 16:45:01 GMT+0800 (中国标准时间)], 
		chunks=[3], chunk=[0], 
		type=[audio/wav], uid=[yangl],  id=[WU_FILE_0], 
		size=[268620636], name=[3.wav],

		//formData的参数
		contentsDto.contentsId=[0000004730], existFlg=[false], 
		status=[file], uploadNum=[0000004730]
		}
		*********************************************************************************************/

		function findFileIcon(file_type) {
			if (file_type == 1) {
				return '&#xe6ed;';
			} else if (file_type == 2) {
				return '&#xe6fc;';
			} else {
				return "&#xe621;";
			}
		}

		function formatUpFileLen(item) {
			var stxt = "";
			if (item.hasOwnProperty('time_len')) {
				stxt += item.time_len + "分钟 ";
			}
			if (item.hasOwnProperty('file_len')) {
				stxt += bytesToSize(item.file_len * 1024);
			}
			return stxt;
		}

		var q_course_id = getUrlParam("id");
		var json_list_class;

		layui.use(['form', 'layer', 'laytpl', 'element', 'upload', 'layedit', 'dialog'], function() {
			var form = layui.form();
			var layer = layui.layer;
			var laytpl = layui.laytpl,
				layedit = layui.layedit,
				element = layui.element(),
				dialog = layui.dialog;

			layui.upload({
				url: '/api/file/upload',
				success: function(res) {
					if (res.code == 0) {
						var sourceId = res.data.paramid.replace("file_", "");
						var ftype = $('input[name="' + res.data.paramid + '"]').attr("lay-type");

						$('#' + sourceId).val(res.data.src);
						$('#file_len').val(res.data.filelen);
						var filetype = 4;
						var imgtype = ".jpeg.jpg.png.gif",
							videotype = ".mp4.3gp.flv.mpeg4",
							audiotype = ".wma.mp3";
						if (imgtype.indexOf(res.data.fileext) >= 0) {
							filetype = 3;
						} else if (videotype.indexOf(res.data.fileext) >= 0) {
							filetype = 1;
						} else if (audiotype.indexOf(res.data.fileext) >= 0) {
							filetype = 2;
						}
						$('#file_type').val(filetype);
						formatUpFile(sourceId, res.data.src, ftype);
						form.render("select");
					} else {
						parent.alertMsg(res.msg);
					}
				}
			});

			function formatUpFile(elid, surl, ftype) {
				if (surl == null || surl == "" || surl == "undefined") {
					return;
				}
				var shtml = '<a href="' + surl + '" target="_blank">' + surl.substr(surl.lastIndexOf('/') + 1) + '</a>';
				$('#div_' + elid).html(shtml);
			}

			// 页面侦听
			$('#mainDivClass').on('click', '.add-class', function() {
				var stitle = $(this).text();
				var cla_id = $(this).attr('data-id');
				openAddClassDiv(stitle);
				$('#course_id').val(q_course_id);
				if (stitle === "+ 添加课节") {
					$('div.upfilediv').hide();
					$('#class_typeid').val(1);
					$('#colname_1st').html('课节名称：');
				} else {
					$('div.upfilediv').show();
					$('#parent_id').val(cla_id);
					$('#class_typeid').val(2);
					$('#colname_1st').html('文件名称：');
				}
				return false;
			});

			$('#mainDivClass').on('click', '.edit-class', function() {
				var stitle = $(this).text();
				var cla_id = $(this).attr('data-id');
				openAddClassDiv(stitle);
				var rows1 = json_list_class.filter(function(e) {
					return e.class_id == cla_id;
				});
				for (var i = 0; i < rows1.length; i++) {
					if (rows1[i].class_typeid == 1) {
						stitle = "编辑课节";
						$('div.upfilediv').hide();
						$('#colname_1st').html('课节名称：');
					} else {
						stitle = "编辑资料";
						$('div.upfilediv').show();
						$('#colname_1st').html('文件名称：');
					}
					$('form[lay-filter="formclass"]').setForm(rows1[i]);
					form.render();
				}

				return false;
			});

			$('#mainDivClass').on('click', '.del-class', function() {
				var cla_id = $(this).attr('data-id');
				dialog.confirm({
					message: '您确定要进行删除吗？上传的文件也将删除，不可恢复！',
					success: function() {
						sendPost("/api/course/delClass", {
							class_id: cla_id
						}, function(res) {
							layer.alert(res.msg, {
								title: '信息提示'
							}, function(idx) {
								if (res.code == 200) {
									window.location.reload();
								}
								layer.close(idx);
							});
						});
					},
					cancel: function() {
						//layer.msg('取消了')
					}
				});
				return false;
			});

			//监听提交
			form.on('submit(formDemo)', function(formData) {
				sendPost("/api/course/saveClass", formData.field, function(res) {
					layer.alert(res.msg, {
						title: '信息提示'
					}, function(idx) {
						if (res.code == 200) {
							window.location.reload();
						}
						layer.close(idx);
					});
				});
				return false;
			});

			function openAddClassDiv(stitle) {
				$('form[lay-filter="formclass"]')[0].reset();
				layer.open({
					title: stitle,
					type: 1,
					area: '550px',
					offset: '50px',
					content: $('#div_add_class')
				});
			}

			function renderListClass(jdata) {
				var getTpl = document.getElementById('tplListClass').innerHTML;
				laytpl(getTpl).render(jdata, function(html) {
					document.getElementById('showListClass').innerHTML += html;
				});
			}

			// 页面初始化
			function page_init() {
				var id = getUrlParam('id');
				// 加载初始化编辑数据
				sendGet("/api/course/getOne", {
					id: q_course_id,
					idesc: 1
				}, function(res) {
					// 初始化编辑数据
					if (res.hasOwnProperty("oneinfo")) {
						$('#front_cover_url').attr('src', res.oneinfo.front_cover_url);
						$('#div_course_name').html('' + res.oneinfo.course_name);
						$('#div_lecturer_name').html('主讲老师：' + res.oneinfo.lecturer_name);
						$('#div_subject_name').html('课程科目：' + res.oneinfo.subject_name);
						$('#div_add_time').html('创建时间：' + res.oneinfo.add_time);
						var powertxt = res.oneinfo.power_id == 1 ? "公开" : "私有";
						$('#div_power_id').html('发布对象：' + powertxt);
					}
					if (res.hasOwnProperty("listclass")) {
						var rows1 = res.listclass.filter(function(e) {
							return e.class_typeid == 1;
						});
						for (var i = 0; i < rows1.length; i++) {
							var rows2 = res.listclass.filter(function(e) {
								return e.parent_id == rows1[i].class_id;
							});
							var jdata = {
								p: rows1[i],
								listdata: rows2
							};
							renderListClass(jdata);
						}
						json_list_class = res.listclass;
					}
					form.render();
				});
			}


			page_init();
		});
	</script>
</body>

#end
